﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Reflection;

namespace Basefr.Runtime.Helpers
{
    public static class ConvertHelper
    {
        public static T ParseEnum<T>(string value)
        {
            return (T)Enum.Parse(typeof(T), string.IsNullOrWhiteSpace(value) ? "None" : value.Trim());
        }

        public static T ParseEnum<T>(int value)
        {
            return Enum.IsDefined(typeof(T), value) ? (T)Enum.ToObject(typeof(T), value) : default(T);
        }

        public static bool TryParseEnumDescription<T>(string description, out T value)
        {
            var result = false;
            var val = default(T);

            typeof(T).GetFields().ToList().ForEach(f =>
            {
                var desc = f.GetCustomAttribute<DescriptionAttribute>();
                if (desc != null && desc.Description == description)
                {
                    result = true;
                    val = (T)f.GetRawConstantValue();
                }
            });

            value = val;
            return result;
        }

        public static int ParseInt(string value)
        {
            return int.TryParse(value, out var intVal) ? intVal : 0;
        }

        public static List<int> ParseIntList(string value, char seperator = ',')
        {
            return string.IsNullOrWhiteSpace(value) ? new List<int>() : value.Split(seperator).Select(ParseInt).ToList();
        }

        public static string ConcatToString(List<int> values, string seperator = ",")
        {
            return values == null || !values.Any() ? string.Empty : string.Join(seperator, values);
        }

        public static float ParseFloat(string value)
        {
            return float.TryParse(value, out var fltVal) ? fltVal : 0;
        }

        public static decimal ParseDecimal(string value)
        {
            return decimal.TryParse(value, out var dcmVal) ? dcmVal : 0;
        }

        public static bool? ParseBool(string value)
        {
            return bool.TryParse(value, out var boolVal) ? boolVal : (bool?)null;
        }

        public static DateTime? ParseDateTime(string value)
        {
            return DateTime.TryParse(value, out var dateVal) ? dateVal : (DateTime?)null;
        }
    }
}
